package com.xb.p39_contentprooviderdemo1;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView tv_context;
    EditText username;
    EditText phoneNum;

    //查询通讯录相关的参数
    String mySelectionClause;   //查询条件
    String[] mySelectionArgs;   //查询参数

    String[] SQL_COLUMN=new String[]{
            ContactsContract.CommonDataKinds.Identity.RAW_CONTACT_ID,    //raw_contact_id
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,         //display_name
            ContactsContract.CommonDataKinds.Phone.NUMBER                //data1
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_context=findViewById(R.id.tv_context);
        username=findViewById(R.id.username);
        phoneNum=findViewById(R.id.phoneNum);

        if (Build.VERSION.SDK_INT>=23)
            checkNeedPermissions();

    }

    //权限申请
    private void checkNeedPermissions(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            //多个权限一起申请
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_CONTACTS
            }, 1);
        }
    }

    //权限申请回调函数，查看权限申请否真的成功
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this,permissions[i] + "未授权",Toast.LENGTH_SHORT).show();
                    continue;
                }
                Toast.makeText(MainActivity.this,permissions[i] + "已授权",Toast.LENGTH_SHORT).show();
            }
        }
    }


    public void clk_query(View view){
        String name=username.getText().toString();
        if(!name.equals("")){//根据名字来删除
            Cursor cursor=getContact(name);
            printQueryResult(cursor);
        }
        Toast.makeText(this, "联系人查询成功", Toast.LENGTH_SHORT).show();
    }

    private Cursor getContact(String name){//根据姓名查询一条记录
        mySelectionClause=ContactsContract.Contacts.DISPLAY_NAME+"=?" ; //查询条件
        mySelectionArgs=new String[]{name};                             //查询参数
        Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,SQL_COLUMN,mySelectionClause,mySelectionArgs,null);
        return cursor;
    }

    public void clk_add(View view){
        String name=username.getText().toString();
        String phone=phoneNum.getText().toString();

        ContentValues values=new ContentValues();
        Uri raw_uri=getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI,values);//获得一个可以保存的URI
        long rawContentID=ContentUris.parseId(raw_uri);//根据空内容的URI获取一个可以保存数据的URI的ID

        /*可以单独插入姓名和号码的使用方式*/
        if(!name.equals(" ")){//插入姓名
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID,rawContentID);
            values.put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,name);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);
        }
        if(!phone.equals(" ")){//插入电话
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID,rawContentID);//同一个ID
            values.put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);//将号码类型设置为移动电话
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,phone);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);
        }


        /*上述代码可以简写为：*/
        /*values.put("raw_contact_id",rawContentID);
        values.put("mimetype","vnd.android.cursor.item/phone_v2");
        values.put("display_name",name);
        values.put("data1",phone);
        values.put("data2","2");
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);*/

        Toast.makeText(this, "联系人数据添加成功", Toast.LENGTH_SHORT).show();
    }

    public void clk_update(View view){
        //1.根据名字查询到具体的ID
        String name=username.getText().toString();
        long rawContentID=0L;
        Uri uri=Uri.parse("content://com.android.contacts/data");
        ContentResolver resolver=getContentResolver();
        ContentValues values=new ContentValues();

        //2.获取要更新的内容
        String phone=phoneNum.getText().toString();
        values.put("data1",phone);

        if(!name.equals("")){//根据名字获取id
            Cursor cursor=getContact(name);
            if (cursor.moveToFirst()){
                rawContentID=cursor.getLong(0);
            }
            resolver.update(uri,values,"mimeType=? and raw_contact_id=?",
                    new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,rawContentID+""});
            cursor.close();
        }
        Toast.makeText(this, "联系人更新成功", Toast.LENGTH_SHORT).show();
    }

    public void clk_delete(View view){
        String name=username.getText().toString();
        if(!name.equals("")){//根据名字来删除
            getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI,ContactsContract.Contacts.DISPLAY_NAME+"=?",new String[]{name});
        }
        Toast.makeText(this, "联系人删除成功", Toast.LENGTH_SHORT).show();
    }

    public void clk_queryall(View view){
        //URI的内容为：content://com.android.contacts/data/phones
        Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,SQL_COLUMN,null,null,null);
        printQueryResult(cursor);
    }

    public void printQueryResult(Cursor cursor){
        if (cursor!=null){
            tv_context.setText("");
            while (cursor.moveToNext()){
                String ID=cursor.getString(0);
                String ContactName=cursor.getString(1);
                String PhoneNum=cursor.getString(2);
                tv_context.append("联系人"+ID+": 姓名="+ContactName+", 电话="+PhoneNum+"\n");
            }
            cursor.close();
        }
    }
}

